import React from 'react';
import { Button, Card, Form, Input, InputNumber, message, Popconfirm, Table, Tooltip } from 'antd';
import SearchForm from '../../components/AutoForm/SearchForm';
import { connect } from 'dva';

const EditableContext = React.createContext();

@connect(({ incomeOrder }) => ({
  requiredCols: incomeOrder.requiredCols,
}))
class EditableCell extends React.Component {
  getInput = dataIndex => {
    switch (dataIndex) {
      case 'pickFee':
        return <InputNumber />;
      case 'arteryFee':
        return <InputNumber />;
      case 'dropoffFee':
        return <InputNumber />;
      case 'workoverFee':
        return <InputNumber />;
      case 'loadupFee':
        return <InputNumber />;
      case 'loadoffFee':
        return <InputNumber />;
      case 'carFee':
        return <InputNumber />;
      case 'fuelFee':
        return <InputNumber />;
      case 'callbackFee':
        return <InputNumber />;
      case 'escortinFee':
        return <InputNumber />;
      case 'tipFee':
        return <InputNumber />;
      case 'shuttleFee':
        return <InputNumber />;
      default:
        return <InputNumber />;
    }
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      requiredCols,
      selectData,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0, padding: 0 }}>
            {getFieldDecorator(dataIndex, {
              rules: requiredCols[title],
              initialValue: record[dataIndex],
            })(this.getInput(dataIndex))}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

@connect(({ incomeOrder, loading }) => ({
  tableLoading: loading.effects['incomeOrder/page'],
  tableData: incomeOrder.pageList,
  pagination: incomeOrder.pagination,
  columns: incomeOrder.columns,
  searchFields: incomeOrder.searchFields,
  searchValues: incomeOrder.searchValues,
  editId: incomeOrder.editId,
  selectionIds: incomeOrder.selectionIds,
  selectedRows: incomeOrder.selectedRows,
}))
class EditableTable extends React.Component {
  rowClassName = (record, index) => {
    if (record.status === 'ENTRY') {
      return 'orderParent';
    }
  };

  componentDidMount() {
    const { dispatch } = this.props;
    this.handleSearch();
    dispatch({
      type: 'customer/selectList',
    });
  }
  cancel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'incomeOrder/handleEdit',
      payload: '',
    });
  };

  save(form, id) {
    const { dispatch } = this.props;
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      dispatch({
        type: 'incomeOrder/save',
        payload: { ...row, id },
      }).then(() => {
        this.handleSearch();
      });
    });
  }

  handleEdit(key) {
    const { dispatch } = this.props;
    dispatch({
      type: 'incomeOrder/handleEdit',
      payload: key,
    });
  }

  handleSearchChange = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'incomeOrder/handleSearchChange',
      payload: fields,
    });
  };

  handleSearch = (flag) => {
    const { dispatch, pagination, searchValues } = this.props;
    let pageParam = { pageSize: pagination.pageSize, current: flag==='btn' ? 1 : pagination.current };
    let searchParam = {};
    Object.keys(searchValues).map(key => {
      searchParam[key] = searchValues[key]['value'];
    });
    const param = {
      ...searchParam,
      ...pageParam,
    };
    dispatch({
      type: 'incomeOrder/page',
      payload: param,
    });
  };

  onChange = (selectedRowKeys, selectedRows) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'incomeOrder/handleSelection',
      payload: { selectedRowKeys, selectedRows },
    });
  };

  onSend = () => {
    const { dispatch, selectionIds } = this.props;
    if (!selectionIds.length) {
      return message.error('请选择一行要发送的数据');
    }
    dispatch({
      type: 'incomeOrder/send',
      payload: selectionIds,
    }).then(() => {
      this.handleSearch();
    });
  };

  render() {
    const {
      columns,
      pagination,
      tableLoading,
      tableData,
      searchFields,
      searchValues,
      editId,
      dispatch,
    } = this.props;
    const components = {
      body: {
        cell: EditableCell,
      },
    };
    columns.forEach(col => {
      if(col.title === '体积单价' || col.title === '重量单价'){
        col.onCell = record => ({
          record,
          inputType: 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: editId === record.id,
        });
      }
      if (col.title === '收入') {
        col.children.forEach(child => {
          if(child.title !== '合计'){
            child.onCell = record => ({
              record,
              inputType: 'text',
              dataIndex: child.dataIndex,
              title: child.title,
              editing: editId === record.id,
            });
          }
        });
      }
    });
    columns.forEach((col, i) => {
      if (col.title === '操作') {
        columns.splice(i, 1);
      }
    });
    columns.push({
      title: '操作',
      width: '120px',
      fixed: 'right',
      render: (text, record) => {
        const editable = editId === record.id;
        return editable ? (
          <span>
            <EditableContext.Consumer>
              {form => (
                <Tooltip placement="bottom" title="保存">
                  <Button size="small" onClick={() => this.save(form, record.id)} icon="save" />
                </Tooltip>
              )}
            </EditableContext.Consumer>
            <Popconfirm
              title="确认取消?"
              cancelText="取消"
              okText="确定"
              onConfirm={() => this.cancel(record.id)}
            >
              <Tooltip placement="bottom" title="撤回">
                <Button size="small" icon="rollback" />
              </Tooltip>
            </Popconfirm>
          </span>
        ) : (
          <Tooltip placement="bottom" title="编辑">
            <Button
              disabled={editId !== '' || record.status !== 'RECEIPT'}
              size="small"
              icon="edit"
              onClick={() => this.handleEdit(record.id)}
            />
          </Tooltip>
        );
      },
    });

    pagination.onChange = (page, pageSize) => {
      let searchParam = {};
      Object.keys(searchValues).map(key => {
        searchParam[key] = searchValues[key]['value'];
      });
      dispatch({
        type: 'incomeOrder/page',
        payload: {
          ...searchParam,
          current: page,
          pageSize,
        },
      });
    };
    pagination.onShowSizeChange = (current, size) => {
      let searchParam = {};
      Object.keys(searchValues).map(key => {
        searchParam[key] = searchValues[key]['value'];
      });
      dispatch({
        type: 'incomeOrder/page',
        payload: {
          ...searchParam,
          current: current,
          pageSize: size,
        },
      });
    };

    const rowSelection = {
      type: 'checkbox',
      selections: this.props.selectedRows,
      selectedRowKeys: this.props.selectionIds,
      onChange: this.onChange,
      getCheckboxProps: record => ({
        disabled: record.status !== 'RECEIPT', // Column configuration not to be checked
      }),
    };

    return (
      <Card bodyStyle={{ padding: 0 }}>
        <SearchForm
          header="实际收入->操作"
          layout="inline"
          isSend={true}
          onFieldsChange={this.handleSearchChange}
          onSubmit={() => {this.handleSearch('btn')}}
          onSend={this.onSend}
          fields={searchFields}
          fieldValue={searchValues}
        />
        <EditableContext.Provider value={this.props.form}>
          <Table
            components={components}
            bordered
            rowKey="id"
            loading={tableLoading}
            dataSource={tableData}
            columns={columns}
            rowSelection={rowSelection}
            rowClassName={this.rowClassName}
            scroll={{ x: 'max-content' }}
            size="small"
            pagination={pagination}
          />
        </EditableContext.Provider>
      </Card>
    );
  }
}

const EditableFormTable = Form.create()(EditableTable);
export default EditableFormTable;
